import Vue from "vue";
import Router from "vue-router";
import NProgress from 'nprogress';
import 'nprogress/nprogress.css'

import auth, {noAuthRoutes, authLogin} from "../util/auth";

import Login from '../views/login';
import NotFound from '../views/404.vue'
import Home from '../views/Home.vue'
import Dashboard from '../views/dashboard/index.vue'
import TableList from '../views/tableList/index'

Vue.use(Router);

const router = new Router({
	routes: [
		{
			path:'/login',
			component: Login,
			name:'Login',
		},
		{
			path:'/',
			component: Home,
			name:'Home',
			redirect: '/dashboard',
		},
		{
			path: '/dashboard',
			component: Home,
			name: 'Dashboard',
			redirect: '/dashboard/index',
			children:[
				{
					path: 'index',
					component: Dashboard,
					name: 'dashboardIndex',
					meta:{
						title: '首页',
					}
				}
			]
		},

		{
			path: '/table-list',
			component: Home,
			name: 'table',
			redirect: '/table-list/index',
			children: [
				{
					path: 'index',
					component: TableList,
					name: 'tableList',
					meta: {
						title: '表格列表'
					}
				}
			]
		},
		{
			path: '*',
			component: NotFound,
			name: 'notFound',
			meta: {
				title: '404',
			}
		},
	]
});

if(authLogin){
	auth.init();
}

router.beforeEach((to, from, next) => {
	NProgress.start();

	if(authLogin){
		const _token = auth.getToken();
		if (to.name === 'Login' && _token) {
			next({
				path: '/'
			})
			return;
		}

		if (!_token && !noAuthRoutes.includes(to.name)) {
			next({
				path: '/login',
				query: {
					redirect: to.fullPath,
				}
			})
			return;
		}
	}

	next();
})

router.afterEach((to, from)=>{
	NProgress.done();
})

export default router;
